package com.iot08.api.service;

import com.iot08.apple.pay.model.*;
import com.iot08.common.entity.app.ApplePayNotifyInfo;
import com.iot08.common.entity.app.ApplePayRenewalInfo;
import com.iot08.common.entity.app.ApplePayTransactionInfo;
import com.iot08.common.service.base.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author cwj
 * @description
 * @date 2025/1/13 17:37
 **/
@Slf4j
@Service
public class ApplePayNotifyInfoService extends BaseService<ApplePayNotifyInfo> {

    /**
     * @description 保存苹果支付异步通知信息
     * @author cwj
     * @param [responseBodyV2DecodedPayload]
     * @return void
     * @date @time 2025/1/13 17:42
     **/
    public void saveOrUpdateApplePayNotifyInfoByResponseBody(ResponseBodyV2DecodedPayload responseBodyV2DecodedPayload,
                                                     JWSTransactionDecodedPayload transactionInfo, JWSRenewalInfoDecodedPayload renewalInfo){
        ApplePayNotifyInfo applePayNotifyInfo = assembleApplePayNotifyInfo(responseBodyV2DecodedPayload, transactionInfo, renewalInfo);
        if(!ObjectUtils.isEmpty(transactionInfo) && StringUtils.isNotEmpty(transactionInfo.getTransactionId())){
            log.info("查询通知记录");
            //查询通知订单是否存在，存在则直接更新订单
            Query query = new Query();
            query.addCriteria(Criteria.where("applePayTransactionInfo.transactionId").is(transactionInfo.getTransactionId())).limit(1);
            ApplePayNotifyInfo apn = this.findOne(query);
            if(ObjectUtils.isNotEmpty(apn)){
                applePayNotifyInfo.setId(apn.getId());
            }
        }
        //保存通知信息,如果之前通知已经存在，则直接替换整个文档内容
        this.save(applePayNotifyInfo);
    }

    /**
     * @description 构建ApplePayNotifyInfo对象
     * @author cwj
     * @param [responseBodyV2DecodedPayload, transactionInfo, renewalInfo]
     * @return com.iot08.common.entity.app.ApplePayNotifyInfo
     * @date @time 2025/1/16 16:20
     **/
    private ApplePayNotifyInfo assembleApplePayNotifyInfo(ResponseBodyV2DecodedPayload responseBodyV2DecodedPayload, JWSTransactionDecodedPayload transactionInfo, JWSRenewalInfoDecodedPayload renewalInfo) {
        ApplePayNotifyInfo applePayNotifyInfo = new ApplePayNotifyInfo();
        Data data = responseBodyV2DecodedPayload.getData();
        Summary summary = responseBodyV2DecodedPayload.getSummary();
        Status status = null;
        if(ObjectUtils.isNotEmpty(data)) {
            status = data.getStatus();
        }
        if(ObjectUtils.isNotEmpty(responseBodyV2DecodedPayload.getNotificationType())) {
            applePayNotifyInfo.setNotificationType(responseBodyV2DecodedPayload.getNotificationType().getValue());
        }
        if(ObjectUtils.isNotEmpty(responseBodyV2DecodedPayload.getSubtype())) {
            applePayNotifyInfo.setSubtype(responseBodyV2DecodedPayload.getSubtype().getValue());
        }
        if(ObjectUtils.isNotEmpty(data) && ObjectUtils.isNotEmpty(data.getAppAppleId())) {
            applePayNotifyInfo.setAppAppleId(data.getAppAppleId());
        }
        if(ObjectUtils.isNotEmpty(data) && StringUtils.isNotEmpty(data.getBundleId())) {
            applePayNotifyInfo.setBundleId(responseBodyV2DecodedPayload.getData().getBundleId());
        }
        if(ObjectUtils.isNotEmpty(summary) && StringUtils.isNotEmpty(summary.getProductId())) {
            applePayNotifyInfo.setProductId(summary.getProductId());
        }
        if(ObjectUtils.isNotEmpty(status)) {
            applePayNotifyInfo.setStatus(status.getValue());
        }
        if(StringUtils.isNotEmpty(responseBodyV2DecodedPayload.getNotificationUUID())) {
            applePayNotifyInfo.setNotificationUuid(responseBodyV2DecodedPayload.getNotificationUUID());
        }
        if(ObjectUtils.isNotEmpty(transactionInfo)) {
            buildApplePayNotifyInfo(transactionInfo, applePayNotifyInfo);
        }
        if(ObjectUtils.isNotEmpty(renewalInfo)){
            buildApplePayRenewalInfo(renewalInfo, applePayNotifyInfo);
        }
        if(ObjectUtils.isNotEmpty(data) && ObjectUtils.isNotEmpty(data.getConsumptionRequestReason())){
            applePayNotifyInfo.setConsumptionRequestReason(data.getConsumptionRequestReason().getValue());
        }
        applePayNotifyInfo.setVersion(responseBodyV2DecodedPayload.getVersion());
        if(ObjectUtils.isNotEmpty(responseBodyV2DecodedPayload.getSignedDate())){
            applePayNotifyInfo.setSignedDate(responseBodyV2DecodedPayload.getSignedDate());
        }
        if(ObjectUtils.isNotEmpty(data) && ObjectUtils.isNotEmpty(data.getEnvironment())){
            applePayNotifyInfo.setEnvironment(data.getEnvironment().getValue());
        }
        if(ObjectUtils.isNotEmpty(summary)) {
            applePayNotifyInfo.setRequestIdentifier(summary.getRequestIdentifier());
            applePayNotifyInfo.setStorefrontCountryCodes(summary.getStorefrontCountryCodes());
            applePayNotifyInfo.setSucceededCount(summary.getSucceededCount());
            applePayNotifyInfo.setFailedCount(summary.getFailedCount());
        }
        if(ObjectUtils.isNotEmpty(responseBodyV2DecodedPayload.getExternalPurchaseToken())){
            applePayNotifyInfo.setExternalPurchaseId(responseBodyV2DecodedPayload.getExternalPurchaseToken().getExternalPurchaseId());
        }
        if(ObjectUtils.isNotEmpty(applePayNotifyInfo.getTokenCreationDate())){
            applePayNotifyInfo.setTokenCreationDate(applePayNotifyInfo.getTokenCreationDate()/1000);
        }
        applePayNotifyInfo.setCreateTime(new Date());
        applePayNotifyInfo.setUpdateTime(new Date());
        return applePayNotifyInfo;
    }

    /**
     * @description 构建ApplePayRenewalInfo对象
     * @author cwj
     * @param [renewalInfo, applePayNotifyInfo]
     * @return void
     * @date @time 2025/1/16 16:19
     **/
    private void buildApplePayRenewalInfo(JWSRenewalInfoDecodedPayload renewalInfo, ApplePayNotifyInfo applePayNotifyInfo) {
        ApplePayRenewalInfo applePayRenewalInfo = new ApplePayRenewalInfo();
        if(ObjectUtils.isNotEmpty(renewalInfo.getExpirationIntent())) {
            applePayRenewalInfo.setExpirationIntent(renewalInfo.getExpirationIntent().getValue());
        }
        applePayRenewalInfo.setOriginalTransactionId(renewalInfo.getOriginalTransactionId());
        if(ObjectUtils.isNotEmpty(renewalInfo.getAutoRenewStatus())) {
            applePayRenewalInfo.setAutoRenewStatus(renewalInfo.getAutoRenewStatus().getValue());
        }
        applePayRenewalInfo.setProductId(renewalInfo.getProductId());
        applePayRenewalInfo.setIsInBillingRetryPeriod(renewalInfo.getIsInBillingRetryPeriod());
        if(ObjectUtils.isNotEmpty(renewalInfo.getPriceIncreaseStatus())) {
            applePayRenewalInfo.setPriceIncreaseStatus(renewalInfo.getPriceIncreaseStatus().getValue());
        }
        if(ObjectUtils.isNotEmpty(renewalInfo.getGracePeriodExpiresDate())) {
            applePayRenewalInfo.setGracePeriodExpiresDate(renewalInfo.getGracePeriodExpiresDate()/1000);
        }
        if(ObjectUtils.isNotEmpty(renewalInfo.getOfferType())) {
            applePayRenewalInfo.setOfferType(renewalInfo.getOfferType().getValue());
        }
        applePayRenewalInfo.setOfferIdentifier(renewalInfo.getOfferIdentifier());
        if(ObjectUtils.isNotEmpty(renewalInfo.getSignedDate())) {
            applePayRenewalInfo.setSignedDate(renewalInfo.getSignedDate()/1000);
        }
        if(ObjectUtils.isNotEmpty(renewalInfo.getRecentSubscriptionStartDate())) {
            applePayRenewalInfo.setRecentSubscriptionStartDate(renewalInfo.getRecentSubscriptionStartDate()/1000);
        }
        if(ObjectUtils.isNotEmpty(renewalInfo.getRenewalDate())) {
            applePayRenewalInfo.setRenewalDate(renewalInfo.getRenewalDate()/1000);
        }
        applePayRenewalInfo.setRenewalPrice(renewalInfo.getRenewalPrice());
        applePayRenewalInfo.setCurrency(renewalInfo.getCurrency());
        if(ObjectUtils.isNotEmpty(renewalInfo.getOfferDiscountType())){
            applePayRenewalInfo.setOfferDiscountType(renewalInfo.getOfferDiscountType().getValue());
        }
        if(!CollectionUtils.isEmpty(renewalInfo.getEligibleWinBackOfferIds())){
            applePayRenewalInfo.setEligibleWinBackOfferIds(renewalInfo.getEligibleWinBackOfferIds());
        }
        applePayNotifyInfo.setApplePayRenewalInfo(applePayRenewalInfo);
    }

    /**
     * @description 构建ApplePayNotifyInfo信息
     * @author cwj
     * @param [transactionInfo, applePayNotifyInfo]
     * @return void
     * @date @time 2025/1/16 15:51
     **/
    private void buildApplePayNotifyInfo(JWSTransactionDecodedPayload transactionInfo, ApplePayNotifyInfo applePayNotifyInfo) {
        ApplePayTransactionInfo applePayTransactionInfo = new ApplePayTransactionInfo();
        applePayTransactionInfo.setCurrency(transactionInfo.getCurrency());
        applePayTransactionInfo.setExpiresDate(transactionInfo.getExpiresDate());
        applePayTransactionInfo.setOriginalTransactionId(transactionInfo.getOriginalTransactionId());
        applePayTransactionInfo.setIsUpgraded(transactionInfo.getIsUpgraded());
        applePayTransactionInfo.setTransactionId(transactionInfo.getTransactionId());
        applePayTransactionInfo.setPrice(ObjectUtils.isNotEmpty(transactionInfo.getPrice())?
                new BigDecimal(transactionInfo.getPrice()).divide(new BigDecimal(1000)):new BigDecimal(0));
        applePayTransactionInfo.setOfferType(transactionInfo.getRawOfferType());
        if(ObjectUtils.isNotEmpty(transactionInfo.getType())){
            applePayTransactionInfo.setType(transactionInfo.getType().getValue());
        }
        applePayTransactionInfo.setQuantity(transactionInfo.getQuantity());
        applePayTransactionInfo.setStorefront(transactionInfo.getStorefront());
        if(ObjectUtils.isNotEmpty(transactionInfo.getPurchaseDate())){
            applePayTransactionInfo.setPurchaseDate(transactionInfo.getPurchaseDate()/1000);
        }
        if(ObjectUtils.isNotEmpty(transactionInfo.getTransactionReason())){
            applePayTransactionInfo.setTransactionReason(transactionInfo.getTransactionReason().getValue());
        }
        applePayTransactionInfo.setOfferIdentifier(transactionInfo.getOfferIdentifier());
        applePayTransactionInfo.setAppAccountToken(transactionInfo.getAppAccountToken().toString());
        applePayTransactionInfo.setOriginalPurchaseDate(transactionInfo.getOriginalPurchaseDate());
        if(ObjectUtils.isNotEmpty(transactionInfo.getOfferDiscountType())){
            applePayTransactionInfo.setOfferDiscountType(transactionInfo.getOfferDiscountType().getValue());
        }
        if(ObjectUtils.isNotEmpty(transactionInfo.getRevocationDate())){
            applePayTransactionInfo.setRevocationDate(transactionInfo.getRevocationDate()/1000);
        }
        if(ObjectUtils.isNotEmpty(transactionInfo.getRevocationReason())){
            applePayTransactionInfo.setRevocationReason(transactionInfo.getRevocationReason().getValue());
        }
        applePayTransactionInfo.setStorefrontId(transactionInfo.getStorefrontId());
        applePayTransactionInfo.setWebOrderLineItemId(transactionInfo.getWebOrderLineItemId());
        if(ObjectUtils.isNotEmpty(transactionInfo.getInAppOwnershipType())){
            applePayTransactionInfo.setInAppOwnershipType(transactionInfo.getInAppOwnershipType().getValue());
        }
        applePayTransactionInfo.setSubscriptionGroupIdentifier(transactionInfo.getSubscriptionGroupIdentifier());
        applePayNotifyInfo.setApplePayTransactionInfo(applePayTransactionInfo);
    }

}
